import { Wechaty, Friendship, Message } from 'wechaty'
import onLogin from './event-operator/login';
import onLogout from './event-operator/loginout';
import onScan from './event-operator/scan';
import Logger from './logger';

// const WECHATY_PUPPET_PADCHAT_TOKEN = 'your-token-here'

// const puppet = 'wechaty-puppet-padchat'
// const puppetOptions = {
//   token: 'WECHATY_PUPPET_PADCHAT_TOKEN',
// }

export default class WechatyManager {

  constructor(){
    this.bot = new Wechaty({ profile: 'wechatyName'});
    this.login = false;
    this.tempJoinRoomContacts = [];
    this.robotOwner = null;
  }

  getContactIndex(contact) {
    return this.tempJoinRoomContacts.findIndex(item => {
      return item.id === contact.id
    })
  }

  async addContactInRooms(contact, rooms) {
    if(!rooms || !rooms.length) {
      contact.say('can not find room');
      return;
    }
    if(rooms.length === 1){
      this.addContactInRoom(contact, rooms[0]);
      return;
    }
    let message = '请选择：<br/>';
    for(let i = 0 ; i < rooms.length ; ++i){
      const topic = await rooms[i].topic();
      const owner = await rooms[i].owner();
      const ownerName = owner && owner.name;
      message += `${i + 1}: 群名称: ${topic}; ${ownerName && `群主: ${ownerName}`}<br/>`
    }
    contact.say(message);
    this.recordTempContact(contact, rooms);
  }

  recordTempContact(contact, rooms){
    const index = this.getContactIndex(contact);
    if(index !== -1){
      this.tempJoinRoomContacts[index] = {
        contact,
        rooms,
      }
    }
    setTimeout(() => {
      const index = this.getContactIndex(contact);
      if(index !== -1){
        this.tempJoinRoomContacts.splice(index, 1);
      }
    }, 1000*60);
  }

  async addContactInRoom(contact, room){
    const memberList = await room.memberList();
    if(memberList.length === 500){
      contact.say('is full');
      room.say(`@${room.owner().name()}, group is full, some people can't join`)
    }else {
      if(memberList.find(item => item.id === contact.id)){
        contact.say('you has in the group');
        return;
      }
      try {
          await room.add(contact)
      } catch(e) {
          console.error(e)
      }
      room.say(`@${contact.name()}, welcome join in`)
    }
  }

  onMessage = async (message) => {
    Logger.debug('receive message from %s, message type %s, message.text %s', message.from().name(), message.type(), message.text());
    if(message.type() === Message.Type.Text) {
      const contact = message.from();
      const text = message.text();
      const msgRoom = message.room();
      if (!msgRoom && contact.id !== this.bot.userSelf().id) {
        const index = this.getContactIndex(contact);
        if(index !== -1){
          this.tempJoinRoomContacts.splice(index, 1);
          if(this.tempJoinRoomContacts[index].rooms && this.tempJoinRoomContacts[index].rooms[text]){
            this.addContactInRoom(contact, this.tempJoinRoomContacts[index].rooms[text]);
            return;
          }
        }
        let findRooms = await this.bot.Room.findAll({ topic: text });
        if(findRooms.length === 0){
          findRooms = await this.bot.Room.findAll({ topic: new RegExp(`^.*${text}.*$`)})
        }
        Logger.info('%s find rooms: %s', text, JSON.stringify(findRooms));
        this.addContactInRooms(contact, findRooms);
      }
    }
  }

  onFriend = (friendship) => {
    if(friendship.type() === Friendship.Type.Receive){
      friendship.accept();
    }
  }

  onRoomInvitation = async (roomInvitation) => {
    try {
      Logger.info("received room-invite event.");
      await roomInvitation.accept()
    } catch (e) {
      Logger.error("join room failed %s", e);
    }
  }

  startBot = async () => {
    Logger.info('start bot begin');
    this.bot.on('scan', onScan);
    this.bot.on('login', (user) => {
      Logger.info('%s login success', user);
      this.login = true;
      onLogin(user);
    });
    this.bot.on('logout', (user) => {
      Logger.info('%s logout success', user);
      this.login = false;
      onLogout(user);
    })
    this.bot.on('message', this.onMessage);
    this.bot.on('friendship', this.onFriend);
    this.bot.on('room-invite', this.onRoomInvitation);
    await this.bot.start();
    Logger.info('start bot end');
  }

  async findRooms(topic){
    if(!this.login){
      await this.startBot();
    }
    return this.bot.Room.findAll(topic ? { topic } : null);
  }

  async findContactFriends(query){
    if(!this.login){
      await this.startBot();
    }
    return this.bot.Contact.findAll(query);
  }

  async saySelf(text) {
    if(!this.login){
      await this.startBot();
    }
    this.bot.userSelf().say(text);
  }

  async sayRobotOwner(text) {
    try {
      if(!this.login){
        await this.startBot();
      }
      Logger.info('sat owner 111');
      if(!this.robotOwner) {
       this.robotOwner = await this.bot.Contact().find({ alias: "呃呃", name: 'owner'});
      }
      console.log(this.robotOwner);
      Logger.info('sat owner 333');
      await this.robotOwner.say(text);
      Logger.info('sat owner 222');
    } catch (error) {
      Logger.info('sat owner err %s', err);
    }
  }
}